package tech.luoyu.ki.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import tech.luoyu.ki.vo.ReturnResult;

/**
 * 控制器支持类
 * 
 * @author Robert
 * @version 2018-1-18
 */
public class BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 参数绑定异常
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public ReturnResult bindException(BindException exception) {
		List<String> list = new ArrayList<>();
		List<FieldError> fieldErrors = exception.getFieldErrors();
		for (FieldError fieldError : fieldErrors) {
			list.add(0, fieldError.getField() + fieldError.getDefaultMessage());
		}
		list.add(0, "数据验证失败：");

		return new ReturnResult(0, addMessage(list.toArray(new String[] {})));
	}
	

	protected String addMessage(String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages) {
			sb.append(message).append(messages.length > 1 ? "<br/>" : "");
		}
		return sb.toString();
	}
	
	/**
	 * 授权异常
	 */
	@ExceptionHandler({ UnauthorizedException.class })
	@ResponseBody
	public ReturnResult unauthorizedException() {
		return new ReturnResult(0, "权限不足！");
	}

	/**
	 * 登录异常
	 */
	@ExceptionHandler({ AuthenticationException.class })
	@ResponseBody
	public ReturnResult authenticationException() {
		return new ReturnResult(0, "未登陆！");
	}

	/**
	 * 运行时异常
	 */
	@ExceptionHandler({ RuntimeException.class })
	@ResponseBody
	public ReturnResult otherException(RuntimeException exception) {
		exception.printStackTrace();
		return new ReturnResult(0, "服务器内部错误！");
	}
}
